<?php

namespace api\modules\v1\models;

use Yii;
use api\common\models\Common;
use api\func\func;
use yii\base\Exception;
use yii\web\NotFoundHttpException;
use yii\data\ActiveDataProvider;
use yii\web\HttpException;
use api\common\models\Mar;
use yii\data\Pagination;
use yii\web\Link;
use \yii\caching\FileDependency;
use api\modules\v1\models\Like;
use \yii\db\Query;
use yii\db\Expression;

class News extends Common
{

    public static function tableName()
    {
        return '{{%news}}';
    }
    /*
     * 根据分类id获取表名称
     * @param $catid
     * @return mixed
     * @throws NotFoundHttpException
     */
    public static function getTable($catid = '')
    {
        return 'news';
        $query = new \yii\db\Query();
        if ($catid == '') {
            throw new NotFoundHttpException('catid参数获取失败');
        }
        if (!$modelid = $query->from('{{%category}}')->select('modelid')->where(['catid' => $catid])->one()) {
            throw new NotFoundHttpException('分类表查找失败catid');
        }

        if (!$tablename = $query->from('{{%model}}')->select('tablename')->where(['modelid' => $modelid['modelid']])->one()) {
            throw new NotFoundHttpException('catid表查找失败');
        }
        return $tablename['tablename'];
    }

    /*
     * 获取简单文章信息
     * @param $id
     * @param $catid
     * @return array|false
     * @throws NotFoundHttpException
     */
    public static function getInfoSim($id,$catid){
        $news_model = self::getTable($catid);
        $db = \Yii::$app->db;
        $HtmlBaseUrl = self::getHtmlBaseUrl();
        $ImgBaseUrl = self::getImgBaseUrl();
        if ($rows = $db->createCommand('SELECT * FROM {{%' . $news_model . '}} as a LEFT JOIN {{%' . $news_model . '_data}} as b on a.id = b.id where a.id = ' . $id)->queryOne()) {
            unset($rows['content']);
            $rows['app_url'] = '';
            if ($rows['url'] != '' && substr($rows['url'], -5) == '.html') { //判断url不能为空 和必须是静态页面
                //$rows['app_url'] = str_replace('www.','m.',str_replace('/html/','/app/',$rows['url']));
                $app_url = parse_url($rows['url']);
                $app_url = $HtmlBaseUrl . $app_url['path'];
                $app_url = str_replace('/html/', '/app/', $app_url);
                $rows['app_url'] = $app_url;
            }

            if($rows['video'] != ''){
                $video = json_decode($rows['video'],true);
                $rows['video'] = $video[0];
                $rows['is_video'] = '1';
            }else{
                $rows['video'] = (object)[];
                $rows['is_video'] = '0';
            }

            if (isset($rows['music']) && $rows['music'] != '') {
                $rows['music'] = json_decode($rows['music'], 1);
                $rows['music'] = $rows['music'][0]['fileurl'];
                if (strripos($rows['music'], 'http://') === false) $rows['music'] = $ImgBaseUrl . $rows['music'];
            }

            if (isset($rows['app_video']) && $rows['app_video'] != '') {
                $rows['app_video'] = json_decode($rows['app_video'], 1);
                $rows['app_video'] = $rows['app_video'][0]['fileurl'];
                if (strripos($rows['app_video'], 'http://') === false) $rows['app_video'] = $ImgBaseUrl . $rows['app_video'];
            }
            return $rows;
        } else {
            throw new NotFoundHttpException('未找到该文章');
        }
    }

    /*
     * 获取新闻详情
     * @param $id
     * @return array|false
     * @throws NotFoundHttpException
     */
    public function getInfo()
    {
        $catid = (int)Yii::$app->request->queryParams['catid'];
        $content_id = (int)Yii::$app->request->queryParams['id'];
        $news_model = self::getTable($catid);
        $db = \Yii::$app->db;
        $HtmlBaseUrl = self::getHtmlBaseUrl();
        $ImgBaseUrl = self::getImgBaseUrl();
        if ($rows = $db->createCommand('SELECT * FROM {{%' . $news_model . '}} as a LEFT JOIN {{%' . $news_model . '_data}} as b on a.id = b.id where a.id = ' . $content_id)->queryOne()) {

            self::updateAll(['look' => new Expression('`look` + 1')], ['id' => $content_id]);

            /*推荐位文章 点赞数据处理*/
            if ($p_data = Recommend::find(['id' => $content_id, 'catid' => $catid, 'posid' => 1])->asArray()->one()) {
                Recommend::updateAll(['look' => new Expression('`look` + 1')], ['id' => $content_id, 'catid' => $catid, 'posid' => 1]);
            }
            /*推荐位文章 点赞数据处理*/

            if($rows['video'] != ''){
                $video = json_decode($rows['video'],true);
                $rows['video'] = $video[0];
                $rows['is_video'] = '1';
            }else{
                $rows['video'] = (object)[];
                $rows['is_video'] = '0';
            }


            unset($rows['content']);
            $rows['app_url'] = '';
            if ($rows['url'] != '' && substr($rows['url'], -5) == '.html') { //判断url不能为空 和必须是静态页面
                //$rows['app_url'] = str_replace('www.','m.',str_replace('/html/','/app/',$rows['url']));
                $app_url = parse_url($rows['url']);
                $app_url = $HtmlBaseUrl . $app_url['path'];
                $app_url = str_replace('/html/', '/app/', $app_url);
                $rows['app_url'] = $app_url;
            }

            if (isset($rows['music']) && $rows['music'] != '') {
                $rows['music'] = json_decode($rows['music'], 1);
                $rows['music'] = $rows['music'][0]['fileurl'];
                if (strripos($rows['music'], 'http://') === false) $rows['music'] = $ImgBaseUrl . $rows['music'];
            }

            if (isset($rows['app_video']) && $rows['app_video'] != '') {
                $rows['app_video'] = json_decode($rows['app_video'], 1);
                $rows['app_video'] = $rows['app_video'][0]['fileurl'];
                if (strripos($rows['app_video'], 'http://') === false) $rows['app_video'] = $ImgBaseUrl . $rows['app_video'];
            }

            /*查询相关文章*/
            $sql = '1';
            $order = '';
            if ($rows['relation']) { //后台存在相关文章
                $relations = explode('|', trim($rows['relation'], '|'));
                $relations = array_diff($relations, array(null));
                $relations = implode(',', $relations);
                $sql = " `id` IN ($relations)";
            } elseif ($rows['keywords']) { //根据后台关键字进行筛选
                $keywords = str_replace(',', ' ', $rows['keywords']);
                $keywords_arr = explode(' ', $keywords);
                $sql = "id != " . $content_id . ' AND (';
                foreach ($keywords_arr as $key => $_k) {
                    $sql .= " `keywords` LIKE '%$_k%' OR";
                }
                $sql = substr($sql, 0, -3);
                $sql .= ')';
                $order = 'look desc,id desc';
            }
            $relations = self::find()->select('id,catid,title,look')->where($sql)->orderBy($order)->limit(5)->all();
            $rows['relation'] = $relations;
            /*查询相关文章*/

            /*查找点赞人*/
            Like::$_tableName = Like::tableExists(Like::formatTable($content_id, Yii::$app->params['table_like']['num'], Yii::$app->params['table_like']['table']));
            $likes = (new \yii\db\Query())
                ->from(Like::$_tableName . ' as a')
                ->leftJoin('{{%user_app}} as b', 'a.uid = b.id')
                ->select('a.*,b.head_img,b.username')
                ->where(['content_id' => $content_id, 'position_type' => 1, 'catid' => $catid])
                ->limit(10)
                ->all();
            foreach ($likes as $k => $v) {
                if ($v['head_img'] != '') {
                    $likes[$k]['head_img'] = substr($v['head_img'], 1);
                }
            }
            $rows['_likes'] = $likes;

            /*查找自己是否点赞*/
            $rows['islike'] = '0';
            $rows['iscollect'] = '0';
            $user = $this->getTokenUserId();
            if ($user != '' && is_array($user)) {
                $likes_uid = array_column($likes, 'uid');
                if (in_array($user['id'], $likes_uid)) {
                    $rows['islike'] = '1';
                }

                /*查找自己是否收藏*/
                if (Collect::findOne(['uid' => $user['id'], 'catid' => $catid, 'content_id' => $content_id])) {
                    $rows['iscollect'] = '1';
                }
                /*查找自己是否收藏*/

                $LookHistory = new LookHistory();
                $LookHistory->add($user['id'],$catid,$content_id);
            }
            /*查找自己是否点赞*/

            /*查找点赞人*/

            /* 查找第三方发布者信息 */
            $third_user = [];
            if($rows['thirdid'] != false && is_numeric($rows['thirdid'])){
                if($_third_user = User::findOne(['id'=>$rows['thirdid']])){
                    $third_user['nickname'] = $_third_user['nickname'] != '' ? $_third_user['nickname'] : func::replace_phone($_third_user['phone']);
                    $third_user['head_img'] = $_third_user['head_img'];
                }
            }
            $rows['third_user'] = count($third_user)==0 ? (object)$third_user : $third_user;
            /* 查找第三方发布者信息 */

            $comment_num = (new Query())
                ->from('{{%comment_app}} as a')
                ->innerJoin('{{%user_app}} as b','a.uid = b.`id`')
                ->where("a.pid = 0 and a.top_pid = 0 and a.content_id = {$rows['id']} and a.catid = {$rows['catid']} and a.status =1")
                ->count();

            //$comment_num = Comment::find()->where("pid = 0 and top_pid = 0 and content_id = {$rows['id']} and catid = {$rows['catid']} and status =1")->count();
            $rows['comment'] = $comment_num;
            return $rows;
        } else {
            throw new NotFoundHttpException('未找到该文章');
        }
    }


    public function search($params)
    {
        if (empty($params['catid'])) throw new NotFoundHttpException('catid参数获取失败');
        if (func::safe_sql($params['catid'])) {
            throw new HttpException(401, '请勿提交非法参数', 0);
        }

        $cahce = Yii::$app->cache;
        $cacheKey = md5('category_' . implode('_', $params));
        $_data = $cahce->get($cacheKey);
        //$_data = false;
        if ($_data === false) {
            $HtmlBaseUrl = self::getHtmlBaseUrl();
            $fields = 'a.id,a.catid,a.title,a.thumb,a.url,a.keywords,a.description,a.username,a.inputtime,a.updatetime,a.listorder,a.like,a.comment,a.istop,a.zst,a.thirdid,b.video';
            $where = 'a.`status`=99 and a.islink =0 and a.catid in (' . $params['catid'] . ')';

            if (!empty($params['search'])) {
                $search = $params['search'];
                if (func::safe_sql($search)) {
                    throw new HttpException(401, '请勿提交非法参数', 0);
                }
                $search = strtr($search, array('%' => '\%', '_' => '\_', '\\' => '\\\\', '\'' => '\\\''));
                $where .= " and (a.title like '%{$search}%' or a.keywords like '%{$search}%' or a.description like '%{$search}%')";
            }else{
                //$where .= ' and a.istop =0 ';
            }

            if (!empty($params['pos'])) {
                $where .= " and (a.posids in(" . $params['pos'] . ")) ";
            }

            $query = ((new Query())
                ->select($fields)
                ->from(self::tableName() .' as a')
                ->leftJoin('{{%news_data}} as b','a.id = b.id')
                ->where($where)
            );


            $query->orderBy('a.inputtime desc');

            $count = $query->count();

            $pagination = new Pagination(['totalCount' => $count]);
            $pagination->defaultPageSize = Yii::$app->params['page_size'];

            $data = $query->offset($pagination->offset)
                ->limit($pagination->limit)
                ->all();

            $this->serializePagination($pagination);

            $ImgBaseUrl = self::getImgBaseUrl();
            foreach ($data as $key => $value) {
                if ($value['thumb'] != '') {
                    $data[$key]['thumb'] = $value['thumb'];
                }

                if ($value['zst'] != '') {
                    $zst = [];
                    $zst_tmp = json_decode($value['zst'], 1);
                    foreach ($zst_tmp as $v) {
                        $zst[] = $v['url'];
                    }
                    $data[$key]['zst'] = $zst;
                } else {
                    $data[$key]['zst'] = [];
                }

                //静态html地址
                if ($value['url'] != '' && substr($value['url'], -5) == '.html') {
                    $app_url = parse_url($value['url']);
                    $app_url = $HtmlBaseUrl . $app_url['path'];
                    $app_url = str_replace('/html/', '/app/', $app_url);
                    $data[$key]['url'] = $app_url;
                }

                if($value['video'] != ''){
                    $video = json_decode($value['video'],true);
                    $data[$key]['video'] = $video[0];
                    $data[$key]['is_video'] = '1';
                }else{
                    $data[$key]['video'] = (object)[];
                    $data[$key]['is_video'] = '0';
                }

                $comment_num = (new Query())
                    ->from('{{%comment_app}} as a')
                    ->innerJoin('{{%user_app}} as b','a.uid = b.`id`')
                    ->where("a.pid = 0 and a.top_pid = 0 and a.content_id = {$value['id']} and a.catid = {$value['catid']} and a.status =1")
                    ->count();
                //$comment_num = Comment::find()->where("pid = 0 and top_pid = 0 and content_id = {$value['id']} and catid = {$value['catid']} and status =1")->count();
                $data[$key]['comment'] = $comment_num;
            }

            $_data = [];
            $_data['items'] = $data;
            $_data['_links'] = $this->linksEnvelope;
            $_data['_meta'] = $this->metaEnvelope;
            $cahce->set($cacheKey, $_data, Yii::$app->params['cache_time_news_list'], new FileDependency(['fileName' => 'cache.txt']));
        }

        return $_data;
    }

    /*
 * 统计系统推送
 * @param int $is_canel
 * @throws NotFoundHttpException
 */
    public function PushTj($content_id,$catid){
        try{
            $news_data = News::getInfoSim($content_id,$catid);
            if($news_data['thirdid'] =='' || $news_data['thirdid'] == 0) return true;
            $user = func::IdToUser($news_data['thirdid']);
            $nickname = $user->nickname != '' ? $user->nickname :func::replace_phone($user->phone);
            $phone = $user->phone;
            $data = '{"User_id":'.$news_data['thirdid'].',"Article_id":'.$content_id.',"Article_type":'.$catid.',"Read_time":"'.date('Y-m-d H:i:s').'","Article_title":"'.$news_data['title'].'","Nickname":"'.$nickname.'","Phone":'.$phone.'}';
            $data = array('data' => $data,'key'=>'c3RhdGlzdGlj');
            $json = func::GoCurl('/api/read/insert',  'POST',$data, $error_msg);
            $array = json_decode($json, true);
            if($array['Code'] != 10000){

            }
        }catch (Exception $e){}

    }


}
